<template>
  <div class="classification">
    <div class="box" @click="$event.stopPropagation()">
      <div class="title">
        <h2>编辑分类</h2>
      </div>
      <div class="inp">
        <el-form ref="modelRef" :rules="rules" :model="modelDate">
          <el-form-item prop="cat_id" label="分类id">
            <el-input
              v-model="modelDate.cat_id"
              size="default"
              placeholder="请输入分类id"
            ></el-input>
          </el-form-item>
          <el-form-item prop="cat_name" label="分类名称">
            <el-input
              v-model="modelDate.cat_name"
              size="default"
              placeholder="请输入分类名称"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="but">
        <el-button>取消</el-button>
        <el-button type="primary" @click="ensure">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useCounterStoreB } from '@/stores/temporary'
import { editClassification } from '@/api/editClassification'
const storeB = useCounterStoreB()
const modelDate = reactive({
  cat_id: 0,
  cat_name: '',
})
const rules = reactive({
  cat_id: [
    { required: true, message: 'id不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: 'id必须为数字', trigger: 'blur' },
  ],
  cat_name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
})
const modelRef = ref()
const ensure = async () => {
  modelRef.value.validate()
  try {
    await editClassification({
      cat_id: modelDate.cat_id,
      cat_name: modelDate.cat_name,
    })
  } catch (err) {
    console.log(err)
  }
}

watch(
  () => storeB.cat_id,
  (val) => {
    modelDate.cat_id = val
  },
)
watch(
  () => storeB.cat_name,
  (val) => {
    modelDate.cat_name = val
  },
)
</script>

<style scoped lang="scss">
.box {
  background: #fff;

  padding: 10px;
  .title {
    h2 {
      margin: 0;
    }
  }
  .but {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
